package org.codegallery.javagal.concurrent;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorTest {
	static final String HTML_START = "<html>"
			+ "<title>HTTP Server in java</title>" + "<body>";

	static final String HTML_END = "</body>" + "</html>";

	public static void main(String[] args) throws Exception {
		testFixedThreadPool();
	}

	private static void testFixedThreadPool() throws Exception {

		Executor pool = Executors.newFixedThreadPool(2,new TestThreadFactory("ServerSocket"));
		ExecutorService cachedPool = Executors.newCachedThreadPool();
		
		ServerSocket socket = new ServerSocket(8888);
		while (true) {
			final Socket connection = socket.accept();
			Runnable r = new Runnable() {
				public void run() {
					try {
						handleRequest(connection);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			};
			pool.execute(r);
		}

	}

	private static void handleRequest(Socket conn) throws Exception {
		System.out.println("The Client " + conn.getInetAddress() + ":"
				+ conn.getPort() + " is connected");
		BufferedReader inFromClient = null;
		DataOutputStream outToClient = null;
		inFromClient = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		outToClient = new DataOutputStream(conn.getOutputStream());

		String requestString = inFromClient.readLine();
		String headerLine = requestString;
		StringTokenizer tokenizer = new StringTokenizer(headerLine);
		String httpMethod = tokenizer.nextToken();
		String httpQueryString = tokenizer.nextToken();

		StringBuffer responseBuffer = new StringBuffer();
		responseBuffer
				.append("<b> This is the HTTP Server Home Page.... </b><BR>");
		responseBuffer.append("The HTTP Client request is ....<BR>");
		System.out.println("The HTTP request string is ....");
		while (inFromClient.ready()) {
			// Read the HTTP complete HTTP Query
			responseBuffer.append(requestString + "<BR>");
			System.out.println(requestString);
			requestString = inFromClient.readLine();
		}

		if (httpMethod.equals("GET")) {
			if (httpQueryString.equals("/")) {
				// The default home page
				sendResponse(200, responseBuffer.toString(), outToClient);
			}
		}

	}

	private static void sendResponse(int statusCode, String responseString,
			DataOutputStream outToClient) throws Exception {

		String statusLine = null;
		String serverdetails = "Server: Java HTTPServer";
		String contentLengthLine = null;
		String fileName = null;
		String contentTypeLine = "Content-Type: text/html" + "\r\n";
		FileInputStream fin = null;

		if (statusCode == 200)
			statusLine = "HTTP/1.1 200 OK" + "\r\n";
		else
			statusLine = "HTTP/1.1 404 Not Found" + "\r\n";

		responseString = HTML_START + responseString + HTML_END;
		contentLengthLine = "Content-Length: " + responseString.length()
				+ "\r\n";

		outToClient.writeBytes(statusLine);
		outToClient.writeBytes(serverdetails);
		outToClient.writeBytes(contentTypeLine);
		outToClient.writeBytes(contentLengthLine);
		outToClient.writeBytes("Connection: close\r\n");
		outToClient.writeBytes("\r\n");
		outToClient.writeBytes(responseString);

		outToClient.close();
	}
}
